package graph;

import java.net.URL;
import java.util.ArrayList;
import java.util.List;

import net.sourceforge.javajson.JsonArray;

import com.gargoylesoftware.htmlunit.WebClient;
import com.gargoylesoftware.htmlunit.html.HtmlPage;

import ernie.database.Database;
import ernie.database.WebMysql;
import ernie.gui.StockChooser;

public class ManualDrawer {

    List<Diagram> diagrams = new ArrayList<Diagram>();
    Database db;
    private StockChooser chooser;

    /**
     * @param args
     * @throws InterruptedException
     */
    public static void main(String[] args) throws InterruptedException {
        new ManualDrawer().run();
    }

    public void run() throws InterruptedException {
        String[] str = new String[1];
        List<String> stockList = new ArrayList<String>();
        WebClient ws = new WebClient();
        try {
            HtmlPage p = ws
                    .getPage("http://ernie.dlinkddns.com:8080/myStocks.php");
            JsonArray json = JsonArray.parse(p.asText());
            for (int i = 0; i < json.size(); i++) {
                stockList.add(json.getString(i));
            }
        } catch (Exception ex) {
            run();
            // JOptionPane.showMessageDialog(null, ex.getClass().getName()+ " "
            // + ex.getMessage());
        }
        chooser = new StockChooser(stockList);
        chooser.setVisible(true);

        str[0] = chooser.doStockSelection();

        createDiagrams(str);

        // diagrams.get(0).setTimePeriod(1320165709000L, 1325090509000L);

        db = new WebMysql("ernie.dlinkddns.com", "avslut");
        while (true) {
            for (Diagram d : diagrams) {
                d.setValues(db);
                setFastUpdate(str[0]);
            }
            Thread.sleep(2000);
        }
    }

    private void setFastUpdate(String name) {
        try {
            new URL("http://ernie.dlinkddns.com:8080/setFast.php?name=" + name)
                    .openConnection().getContent();
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }

    private void createDiagrams(String[] str) {
        for (String s : str) {
            diagrams.add(new Diagram(s, 800, 600, true)); // today
        }
    }

}
